﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;

namespace Maltose.MessageQueue
{
    /// <summary>
    /// 消息队列连接
    /// </summary>
    public class MessageQueueConnect : MessageQueueHostConfig
    {
        /// <summary>
        /// 连接配置
        /// </summary>
        static ConnectionFactory factory;

        /// <summary>
        /// 客户端主机名称
        /// </summary>
        public string ClientProvidedName { get; private set; }

        /// <summary>
        /// 连接
        /// </summary>
        static IConnection connection;

        //锁
        static readonly object connLock = new object();

        /// <summary>
        /// MQ连接
        /// </summary>
        public IConnection Connection
        {
            get
            {
                if (connection == null || connection.IsOpen == false)
                {

                    lock (connLock)
                    {
                        if (connection == null || connection.IsOpen == false)
                        {

                            connection = factory.CreateConnection(ClientProvidedName);
                            return connection;
                        }
                    }
                    return connection;
                }
                return connection;
            }
        }

        /// <summary>
        /// 消息队列连接
        /// </summary>
        /// <param name="clientProvidedName">客户端主机名称</param>
        public MessageQueueConnect(string clientProvidedName = "")
        {
            ClientProvidedName = clientProvidedName;
            factory = new ConnectionFactory()
            {
                HostName = HostName,
                Port = Port,
                UserName = UserName,
                Password = Password
            };
        }
    }
}
